package com.bainuo.doctor.common.image_support.imghandle.crop;


import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;

import com.bainuo.doctor.common.image_support.imghandle.Bean.ImageUploadInfo;
import com.bainuo.doctor.common.network_engine.UpFileServerApi;
import com.blankj.utilcode.utils.Utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;

import com.global.Global;


/**
 * Created by faraway on 15/2/17.
 */
public class ImageAvatarCrop extends BaseCrop {

    private ImageUploadInfo imageInfo;

    private String packId;

    public ImageAvatarCrop(String packId){
        this.packId = packId;
    }

    @Override
    public void cropImage(ImageUploadInfo info) {
//        super.cropImage(info);
        imageInfo = info;
//        Intent intent = new Intent(activity,ImageCropAvtivity.class);
//        intent.putExtra(ImageCropAvtivity.BUNDLE_IMAGEPATH,info.getSrcPath());
//        activity.startActivityForResult(intent,code);

        startPhotoZoom(info.getSrcPath());
    }


    String mSelectPath;
    public void startPhotoZoom(String photoPath) {
        try {
            // 获取系统时间 然后将裁剪后的图片保存至指定的文件夹
            SimpleDateFormat sDateFormat = new SimpleDateFormat(
                    "yyyyMMddhhmmss");
            String address = sDateFormat.format(new java.util.Date());
            mSelectPath =  Global.getPathWithRoot("tmp")+"/"+address+".jpg.tmp";

            Uri imageUri = getUri(address);

            final Intent intent = new Intent("com.android.camera.action.CROP");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                // 照片URL地址
                File file = new File(photoPath);
                if(file.exists()){
                    intent.setDataAndType(getUri2(photoPath), "image/*");
                }else{
                    return;
                }

            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
//            intent.putExtra("outputX", 540);
//            intent.putExtra("outputY", 540);
            // 输出路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            // 输出格式
            intent.putExtra("outputFormat",
                    Bitmap.CompressFormat.JPEG.toString());
            // 不启用人脸识别
            intent.putExtra("noFaceDetection", true);
            intent.putExtra("return-data", false);
        //将存储图片的uri读写权限授权给剪裁工具应用
            List<ResolveInfo> resInfoList = Utils.getContext().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                Utils.getContext().grantUriPermission(packageName, imageUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            ((Activity)activity).startActivityForResult(intent, code);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private Uri getUri(String address) {
        File path = new File(Global.getPathWithRoot("tmp")+"/"+address+".jpg.tmp");
        //由于一些Android 7.0以下版本的手机在剪裁保存到URI会有问题，所以根据版本处理下兼容性
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(Utils.getContext(), packId + ".fileProvider", path);
//            return FileProvider.getUriForFile(Utils.getContext(), BuildConfig.APPLICATION_ID + ".fileProvider", path);
        } else {
            return Uri.fromFile(path);
        }
    }

    private Uri getUri2(String file) {
        File path = new File(file);
        //由于一些Android 7.0以下版本的手机在剪裁保存到URI会有问题，所以根据版本处理下兼容性
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(Utils.getContext(), packId + ".fileProvider", path);
//            return FileProvider.getUriForFile(Utils.getContext(), BuildConfig.APPLICATION_ID + ".fileProvider", path);
//            return null;
        } else {
            return Uri.fromFile(path);
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == code ) {
            if(data != null){
                String path = mSelectPath;
                imageInfo.setUploadPath(path);
//                imageInfo.setDeleteOnUploaded(true);
                imageInfo.setUploadType(UpFileServerApi.TYPE_AVATAR);
                if (listener != null)
                    listener.onCropend(imageInfo);
            }

        }
    }
}
